package com.neusoft.tmall.ums.controller;

import com.google.common.collect.Maps;
import com.neusoft.tmall.bo.LoginParams;
import com.neusoft.tmall.ums.service.UmsAdminService;
import com.neusoft.tmall.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("admin")
public class UmsAdminController {
    private static final Logger logger = LoggerFactory.getLogger(UmsAdminController.class);

    @Autowired
    private UmsAdminService umsAdminService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @GetMapping("hello")
    public Object hello(){
        return "hello Security";
    }

    @GetMapping("welcome")
    public Object welcome() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        logger.info("当前登录的用户对象：{}",authentication);
        return "welcome Security";
    }

    /**
     * 登录拦截的流程
     *      1、编写登录拦截器配置到SpringBoot中
     *      2、拦截器是以什么来判断你是否登录过？
     *          是通过session里面放一个值，该值一般是用户对象
     * @param loginParams
     * @return
     */
    @PostMapping("login")
    public Object login(@RequestBody LoginParams loginParams){
        System.out.println("登录用户名："+loginParams.getUsername());
        logger.info("usename:{}, password:{}", loginParams.getUsername(), loginParams.getPassword());
        UserDetails userDetails = umsAdminService.loadUserByUsername(loginParams.getUsername());
        System.out.println("密码为："+userDetails.getPassword());
        //matches里面的两个参数不要放错位置，位置1是没有加密过的，位置2是加密过的
        if(!passwordEncoder.matches(loginParams.getPassword(),userDetails.getPassword())){
            return "账号或密码错误";
        }
        //验证完成用户名和密码之后，必须告诉Security已经登录成功了
        //UsernamePasswordAuthenticationToken保存用户信息
        Object userDetails1;
        Object principal;
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities());
        //保存到Security的上下文当中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        HttpServletRequest servletRequest;
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        String tokenHead = jwtTokenUtil.getTokenHead();
        Map<String, Object> map = Maps.newHashMap();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return map;
    }

    @GetMapping("logout")
    public Object logout(){
        SecurityContextHolder.clearContext();
        return "登出成功";
    }
}
